import { StateCreator } from 'zustand';

export type FishState = {
  fish: number;
};

export type FishActions = {
  addFish: (count: number) => void;
  removeAllFish: () => void;
  asyncAddFish: () => Promise<string>;
};

const sleep = () => new Promise<void>(resolve => {
  setTimeout(() => {
    resolve();
  }, 1500);
});

// MARK: 3、创建一个 state slice
export const createFishSlice: StateCreator<
  FishState & FishActions,
  [["zustand/immer", never]],
  [],
  FishState & FishActions
> = 
  (set) => ({
    fish: 0,
    // MARK: 4、利用 immer 可以直接修改 state
    addFish: (count) => set((state) => {
      state.fish += count;
    }),
    removeAllFish: () => set(state => {
      state.fish = 0;
    }),
    // MARK: 5、无缝支持异步操作
    asyncAddFish: async () => {
      await sleep();
      set(state => {
        state.fish += 10;
      })
      return 'success';
    }
  });
